package cn.easier.activity.console.service.impl;

import cn.easier.activity.console.entity.ActivityConsoleUser;
import cn.easier.activity.console.entity.PeriodicalMessageParams;
import cn.easier.activity.console.repository.ActivityPeriodicalRepository;
import cn.easier.activity.console.service.ActivityPeriodicalService;
import cn.easier.activity.console.service.ActivityTemplateInfoService;
import cn.easier.activity.web.entity.ActivityTemplateInfo;
import cn.easier.activity.web.entity.PeriodicalMessage;
import cn.easier.club.base.dto.ResultInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 期刊ServiceImpl
 */
@Service
@Transactional
public class ActivityPeriodicalServiceImpl implements ActivityPeriodicalService {

    private static final Logger logger = LoggerFactory.getLogger(ActivityPeriodicalServiceImpl.class);

    @Value("${metadata.configuration.foreground-static-link}")
    public String foregroundStaticLink;

    //活动状态
    private static final Integer RELEASE_STATE = 1;
    private static final Integer DELETE_STATE = 2;

    private final ActivityPeriodicalRepository activityPeriodicalRepository;
    private final ActivityTemplateInfoService activityTemplateInfoService;

    public ActivityPeriodicalServiceImpl(ActivityPeriodicalRepository activityPeriodicalRepository, ActivityTemplateInfoService activityTemplateInfoService) {
        this.activityPeriodicalRepository = activityPeriodicalRepository;
        this.activityTemplateInfoService = activityTemplateInfoService;
    }

    @Override
    public List<Object> getMessage(Integer activityId, int pageNum, int pageSize) {
        int pageCount = pageNum * pageSize;
        List<PeriodicalMessage> allBy = new ArrayList<>();
        long allByCount = 0L;
        ActivityConsoleUser principal = this.getPrincipal();
        String authoritiesStr = principal.getAuthoritiesStr();
        if (authoritiesStr.equals("ROLE_USER_SELF")) {
            String username = principal.getUsername();
            allBy = activityPeriodicalRepository.findByCreateByAndCreateTime(username, activityId, pageCount, pageSize);
            allByCount = activityPeriodicalRepository.findAllByCount(username, activityId);
        } else {
            allBy = activityPeriodicalRepository.findBy(activityId, pageCount, pageSize);
            allByCount = activityPeriodicalRepository.findByCount(activityId);
        }
        List<Object> returnList = new ArrayList<>(allBy);
        returnList.add(allByCount);
        return returnList;
    }

    @Override
    public ResultInfo getPeriodicalTitle() {
        List<PeriodicalMessage> allPeriodicalTitle = new ArrayList<>();
        ActivityConsoleUser principal = this.getPrincipal();
        String authoritiesStr = principal.getAuthoritiesStr();
        if (authoritiesStr.equals("ROLE_USER_SELF")) {
            String username = principal.getUsername();
            allPeriodicalTitle = activityPeriodicalRepository.findByCreateByAndStatusIsNotOrderByCreateTimeDesc(username, 2);
        } else {
            allPeriodicalTitle = activityPeriodicalRepository.findByStatusNotOrderByCreateTimeDesc(2);
        }
        return new ResultInfo("SUCCESS", "查询活动名称成功", allPeriodicalTitle);
    }

    @Override
    public ResultInfo addPeriodicalMessage(PeriodicalMessageParams params) {
        ActivityConsoleUser principal = this.getPrincipal();
        String username = principal.getUsername();
        ActivityTemplateInfo activityTemplateInfo = activityTemplateInfoService.findOne(params.getTemplateId());
        if (activityTemplateInfo == null) {
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "活动创建失败，找不到对应的模板信息", null);
        }
        try {
            PeriodicalMessage periodicalMessage = new PeriodicalMessage();
            periodicalMessage.setCreateBy(username);
            periodicalMessage.setContent(params.getContent());
            periodicalMessage.setAbstractText(params.getAbstractText());
            periodicalMessage.setTitle(params.getTitle());
            periodicalMessage.setStatus(0);
            periodicalMessage.setBackgroundImage(params.getBackgroundImage());
            periodicalMessage.setTemplateId(params.getTemplateId());
            periodicalMessage.setReleaseFlag(false);
            periodicalMessage.setForegroundLink("");
            periodicalMessage.setTypeIdentification(activityTemplateInfoService.getActivityType(periodicalMessage.getTemplateId()));
            periodicalMessage.setCreateTime(new Date());
            PeriodicalMessage save = activityPeriodicalRepository.save(periodicalMessage);
            logger.info("期刊创建成功: =>{}", periodicalMessage);
            return new ResultInfo("SUCCESS", "期刊创建成功", save);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("活动创建异常,activityTemplateInfo: =>{}", params);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "期刊创建异常", null);
        }
    }

    @Override
    public ResultInfo updatePeriodicalMessage(PeriodicalMessageParams params) {
        ActivityConsoleUser principal = this.getPrincipal();
        ActivityTemplateInfo activityTemplateInfo = activityTemplateInfoService.findOne(params.getTemplateId());
        if (activityTemplateInfo == null) {
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "活动编辑失败，找不到对应的模板信息", null);
        }
        try {
            PeriodicalMessage periodicalMessage = activityPeriodicalRepository.findOne(params.getId());
            periodicalMessage.setContent(params.getContent());
            periodicalMessage.setAbstractText(params.getAbstractText());
            periodicalMessage.setTitle(params.getTitle());
            PeriodicalMessage save = activityPeriodicalRepository.save(periodicalMessage);
            logger.info("期刊编辑成功: =>{}", periodicalMessage);
            return new ResultInfo("SUCCESS", "期刊编辑成功", save);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("活动编辑异常,activityTemplateInfo: =>{}", params);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "期刊编辑异常", null);
        }
    }

    @Override
    public ResultInfo release(Integer id) {
        PeriodicalMessage periodicalMessage = null;
        String user = this.getPrincipal().getUsername();
        String authoritiesStr = this.getPrincipal().getAuthoritiesStr();
        try {
            if (authoritiesStr.equals("ROLE_USER_SUPERADMIN") || authoritiesStr.equals("ROLE_USER_ADMIN")) {
                periodicalMessage = activityPeriodicalRepository.findOne(id);
            } else {
                periodicalMessage = activityPeriodicalRepository.findByCreateByAndStatusIsNotAndId(user, 2, id);
            }
            if (periodicalMessage == null) {
                logger.info("期刊发布失败，没有找到对应的期刊活动, id: =>{}", id);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "期刊发布失败，找不到指定的期刊活动", null);
            }
            String foregroundLink = foregroundStaticLink + "?activityId=" + id + "&typeIdentification=" + periodicalMessage.getTypeIdentification();
            int release = activityPeriodicalRepository.release(RELEASE_STATE, foregroundLink, id, user);
            logger.info("发布指定活动：=>{}, id: =>{}", release > 0 ? "成功" : "失败", id);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "活动发布成功", foregroundLink);
        } catch (Exception e) {
            logger.info("发布指定活动异常,id：=>{}", id);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "活动发布异常", null);
        }
    }

    @Override
    public ResultInfo delMessage(Integer id) {
        PeriodicalMessage one = activityPeriodicalRepository.findOne(id);
        if (one == null) {
            return new ResultInfo("ERROR", "未查询到该期刊信息", null);
        }
        one.setStatus(DELETE_STATE);
        activityPeriodicalRepository.save(one);
        return new ResultInfo("SUCCESS", "删除成功", null);
    }

    @Override
    public Boolean runOrPauseOrSuperUser(Boolean release, Integer id) {
        int changeNum = activityPeriodicalRepository.runOrPauseOrSuperUser(release, id);
        return changeNum > 0;
    }

    @Override
    public Boolean runOrPause(Boolean release, Integer id, String user) {
        int changeNum = activityPeriodicalRepository.runOrPause(release, id, user);
        return changeNum > 0;
    }

    @Override
    public ResultInfo getMessageById(Integer id) {
        PeriodicalMessage one = activityPeriodicalRepository.findOne(id);
        return new ResultInfo("SUCCESS", "查询成功", one);
    }

    /*
     *PostAuthorize 已经支持EL 表达式
     */
    @RequestMapping(value = "/getPrincipal", method = RequestMethod.GET)
    @PostAuthorize(" returnObject!=null && returnObject.authoritiesStr == authentication.name ")
    public ActivityConsoleUser getPrincipal() {
        Object pricipal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ActivityConsoleUser activityConsoleUser;
        if (pricipal instanceof ActivityConsoleUser) {
            activityConsoleUser = (ActivityConsoleUser) pricipal;
        } else {
            activityConsoleUser = null;
        }
        return activityConsoleUser;
    }
}
